<template>
  <div class="equipment-failure-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备故障管理</span>
          <div class="header-operations">
            <el-button type="danger" @click="handleReport">故障报修</el-button>
            <el-button type="primary" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="故障单号">
          <el-input
            v-model="queryForm.failureNo"
            placeholder="请输入故障单号"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="queryForm.equipmentName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="故障类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择故障类型"
            clearable
          >
            <el-option
              v-for="item in failureTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报修日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 故障列表 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="failureNo" label="故障单号" width="130" />
        <el-table-column prop="equipmentCode" label="设备编码" width="120" />
        <el-table-column prop="equipmentName" label="设备名称" width="150" />
        <el-table-column prop="type" label="故障类型" width="120">
          <template #default="scope">
            <el-tag :type="getFailureTypeTag(scope.row.type)">
              {{ getFailureTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="故障等级" width="100">
          <template #default="scope">
            <el-tag :type="getFailureLevelTag(scope.row.level)">
              {{ getFailureLevelText(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reportTime" label="报修时间" width="150" />
        <el-table-column prop="reporter" label="报修人" width="100" />
        <el-table-column prop="handler" label="处理人" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="downtime" label="停机时长" width="120">
          <template #default="scope">
            {{ formatDowntime(scope.row.downtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === 'pending'"
              >处理</el-button
            >
            <el-button link type="primary" @click="handleViewDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              link
              type="success"
              @click="handleComplete(scope.row)"
              v-if="scope.row.status === 'processing'"
              >完成</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 故障报修对话框 -->
    <el-dialog v-model="reportDialogVisible" title="故障报修" width="60%">
      <el-form
        ref="reportFormRef"
        :model="reportForm"
        :rules="reportRules"
        label-width="100px"
      >
        <el-form-item label="设备选择" prop="equipmentId">
          <el-select v-model="reportForm.equipmentId" placeholder="请选择设备">
            <el-option
              v-for="item in equipmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障类型" prop="type">
          <el-select v-model="reportForm.type" placeholder="请选择故障类型">
            <el-option
              v-for="item in failureTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障等级" prop="level">
          <el-select v-model="reportForm.level" placeholder="请选择故障等级">
            <el-option
              v-for="item in failureLevels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障描述" prop="description">
          <el-input
            v-model="reportForm.description"
            type="textarea"
            rows="3"
            placeholder="请描述故障现象和影响"
          />
        </el-form-item>
        <el-form-item label="故障图片">
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReportSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 故障处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="故障处理" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="故障单号">{{
          currentFailure.failureNo
        }}</el-descriptions-item>
        <el-descriptions-item label="设备编码">{{
          currentFailure.equipmentCode
        }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{
          currentFailure.equipmentName
        }}</el-descriptions-item>
        <el-descriptions-item label="故障类型">{{
          getFailureTypeText(currentFailure.type)
        }}</el-descriptions-item>
        <el-descriptions-item label="故障等级">{{
          getFailureLevelText(currentFailure.level)
        }}</el-descriptions-item>
        <el-descriptions-item label="报修时间">{{
          currentFailure.reportTime
        }}</el-descriptions-item>
      </el-descriptions>

      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item label="故障原因" prop="cause">
          <el-input
            v-model="processForm.cause"
            type="textarea"
            rows="2"
            placeholder="请输入故障原因分析"
          />
        </el-form-item>
        <el-form-item label="解决方案" prop="solution">
          <el-input
            v-model="processForm.solution"
            type="textarea"
            rows="2"
            placeholder="请输入解决方案"
          />
        </el-form-item>
        <el-form-item label="处理措施" prop="measures">
          <el-input
            v-model="processForm.measures"
            type="textarea"
            rows="2"
            placeholder="请输入具体处理措施"
          />
        </el-form-item>
        <el-form-item label="备件更换">
          <el-button type="primary" @click="handleAddPart">添加备件</el-button>
          <el-table :data="processForm.parts" border style="margin-top: 10px">
            <el-table-column label="备件名称" width="200">
              <template #default="scope">
                <el-select v-model="scope.row.partId" placeholder="请选择备件">
                  <el-option
                    v-for="item in partsOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template #default="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleRemovePart(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 查询表单数据
const queryForm = reactive({
  failureNo: "",
  equipmentName: "",
  type: "",
  status: "",
  dateRange: [],
});

// 故障类型选项
const failureTypes = [
  { value: "mechanical", label: "机械故障" },
  { value: "electrical", label: "电气故障" },
  { value: "hydraulic", label: "液压故障" },
  { value: "pneumatic", label: "气动故障" },
  { value: "control", label: "控制系统故障" },
  { value: "other", label: "其他故障" },
];

// 故障等级选项
const failureLevels = [
  { value: "critical", label: "重大故障" },
  { value: "major", label: "主要故障" },
  { value: "minor", label: "次要故障" },
];

// 状态选项
const statusOptions = [
  { value: "pending", label: "待处理" },
  { value: "processing", label: "处理中" },
  { value: "completed", label: "已完成" },
  { value: "closed", label: "已关闭" },
];

// 设备选项
const equipmentOptions = [
  { value: "EQ001", label: "数控车床-EQ001" },
  { value: "EQ002", label: "加工中心-EQ002" },
  { value: "EQ003", label: "三坐标测量仪-EQ003" },
  { value: "EQ004", label: "空气压缩机-EQ004" },
  { value: "EQ005", label: "工业机器人-EQ005" },
];

// 备件选项
const partsOptions = [
  { value: "P001", label: "轴承-6205-2RS" },
  { value: "P002", label: "油封-TC20×35×7" },
  { value: "P003", label: "同步带-5M-400" },
  { value: "P004", label: "电机-Y90L-4" },
  { value: "P005", label: "传感器-E3Z-T61" },
];

// 表格数据
const tableData = ref([
  {
    failureNo: "F202403001",
    equipmentCode: "EQ001",
    equipmentName: "数控车床",
    type: "mechanical",
    level: "major",
    reportTime: "2024-03-20 08:30:00",
    reporter: "张三",
    handler: "李四",
    status: "processing",
    downtime: 120, // 分钟
  },
  {
    failureNo: "F202403002",
    equipmentCode: "EQ002",
    equipmentName: "加工中心",
    type: "electrical",
    level: "critical",
    reportTime: "2024-03-19 14:20:00",
    reporter: "王五",
    handler: "赵六",
    status: "completed",
    downtime: 360,
  },
  {
    failureNo: "F202403003",
    equipmentCode: "EQ003",
    equipmentName: "三坐标测量仪",
    type: "control",
    level: "minor",
    reportTime: "2024-03-20 09:15:00",
    reporter: "李四",
    handler: "",
    status: "pending",
    downtime: 45,
  },
  {
    failureNo: "F202403004",
    equipmentCode: "EQ004",
    equipmentName: "空气压缩机",
    type: "pneumatic",
    level: "major",
    reportTime: "2024-03-18 16:40:00",
    reporter: "赵六",
    handler: "张三",
    status: "closed",
    downtime: 240,
  },
  {
    failureNo: "F202403005",
    equipmentCode: "EQ005",
    equipmentName: "工业机器人",
    type: "hydraulic",
    level: "critical",
    reportTime: "2024-03-20 10:30:00",
    reporter: "王五",
    handler: "李四",
    status: "processing",
    downtime: 180,
  },
]);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 当前故障
const currentFailure = ref({});

// 对话框显示控制
const reportDialogVisible = ref(false);
const processDialogVisible = ref(false);

// 报修表单
const reportForm = reactive({
  equipmentId: "",
  type: "",
  level: "",
  description: "",
});

// 处理表单
const processForm = reactive({
  cause: "",
  solution: "",
  measures: "",
  parts: [],
});

// 表单校验规则
const reportRules = {
  equipmentId: [{ required: true, message: "请选择设备", trigger: "change" }],
  type: [{ required: true, message: "请选择故障类型", trigger: "change" }],
  level: [{ required: true, message: "请选择故障等级", trigger: "change" }],
  description: [{ required: true, message: "请输入故障描述", trigger: "blur" }],
};

const processRules = {
  cause: [{ required: true, message: "请输入故障原因", trigger: "blur" }],
  solution: [{ required: true, message: "请输入解决方案", trigger: "blur" }],
  measures: [{ required: true, message: "请输入处理措施", trigger: "blur" }],
};

// 获取故障类型标签
const getFailureTypeTag = (type) => {
  const typeMap = {
    mechanical: "",
    electrical: "warning",
    hydraulic: "info",
    pneumatic: "success",
    control: "danger",
    other: "info",
  };
  return typeMap[type];
};

// 获取故障类型文本
const getFailureTypeText = (type) => {
  const typeMap = {
    mechanical: "机械故障",
    electrical: "电气故障",
    hydraulic: "液压故障",
    pneumatic: "气动故障",
    control: "控制系统故障",
    other: "其他故障",
  };
  return typeMap[type];
};

// 获取故障等级标签
const getFailureLevelTag = (level) => {
  const levelMap = {
    critical: "danger",
    major: "warning",
    minor: "info",
  };
  return levelMap[level];
};

// 获取故障等级文本
const getFailureLevelText = (level) => {
  const levelMap = {
    critical: "重大故障",
    major: "主要故障",
    minor: "次要故障",
  };
  return levelMap[level];
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: "warning",
    processing: "primary",
    completed: "success",
    closed: "info",
  };
  return statusMap[status];
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: "待处理",
    processing: "处理中",
    completed: "已完成",
    closed: "已关闭",
  };
  return statusMap[status];
};

// 格式化停机时长
const formatDowntime = (minutes) => {
  if (!minutes) return "-";
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
};

// 查询方法
const handleSearch = () => {
  ElMessage.success("查询成功");
};

const handleReset = () => {
  queryForm.failureNo = "";
  queryForm.equipmentName = "";
  queryForm.type = "";
  queryForm.status = "";
  queryForm.dateRange = [];
};

// 报修方法
const handleReport = () => {
  reportDialogVisible.value = true;
  Object.assign(reportForm, {
    equipmentId: "",
    type: "",
    level: "",
    description: "",
  });
};

const handleReportSubmit = async () => {
  if (!reportFormRef.value) return;
  await reportFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("报修成功");
      reportDialogVisible.value = false;
    }
  });
};

// 处理方法
const handleProcess = (row) => {
  currentFailure.value = row;
  processDialogVisible.value = true;
  Object.assign(processForm, {
    cause: "",
    solution: "",
    measures: "",
    parts: [],
  });
};

const handleAddPart = () => {
  processForm.parts.push({
    partId: "",
    quantity: 1,
  });
};

const handleRemovePart = (index) => {
  processForm.parts.splice(index, 1);
};

const handleProcessSubmit = async () => {
  if (!processFormRef.value) return;
  await processFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("处理成功");
      processDialogVisible.value = false;
    }
  });
};

// 完成方法
const handleComplete = (row) => {
  ElMessageBox.confirm("确认完成故障处理？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ElMessage.success("处理完成");
  });
};

// 其他方法
const handleViewDetail = (row) => {
  ElMessage.success("查看详情：" + row.failureNo);
};

const handleExport = () => {
  ElMessage.success("导出成功");
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.equipment-failure-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>
